// 给定一个非空整数数组，除了某个元素只出现一次以外，其余每个元素均出现两次。找出那个只出现了一次的元素。

let nums = [4, 1, 2, 1, 2];


// set 1
let singleNumber = nums => {
  let mySet = new Set();
  for (let i = 0; i < nums.length; i++) {
    if (mySet.has(nums[i])) {
      mySet.delete(nums[i]);
    } else {
      mySet.add(nums[i]);
    }
  }
  return [...mySet];
}

// set 2
let singleNumber2 = nums => {
  let mySet = new Set();
  let res = 0;
  for (let i = 0; i < nums.length; i++) {
    if (!mySet.has(nums[i])) mySet.add(nums[i]);
    res += nums[i];
  }
  return [
    [...mySet].reduce((pre, cur) => pre + cur) * 2 - res
  ];
}

/**
 * 位运算 ^
 * 1.交换律：a ^ b ^ c  <=> a ^ c ^ b
   2.任何数与0异或为本身 0 ^ n => n
   3.相同的数异或为0: n ^ n => 0
 */

let singleNumber3 = nums => {
  let res = nums[0];
  for (let i = 1; i < nums.length; i++) {
    res ^= nums[i];
  }
  return [res];
}


console.log(singleNumber2(nums))